﻿using Application.ProductImgService;
using Application.ProductService;
using Domain.Entity.bs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class ProductImgController : ControllerBase
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly IProductImgService productImgService;

        public ProductImgController(IWebHostEnvironment webHostEnvironment, IProductImgService productImgService)
        {
            this.webHostEnvironment = webHostEnvironment;
            this.productImgService = productImgService;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImg(IFormFileCollection files)
        {
            if (files == null || files.Count == 0)
            {
                return BadRequest("没有上传文件.");
            }

            var uploadedFiles = new List<object>();

            foreach (var file in files)
            {
                if (file.Length == 0) continue;

                // 生成文件名
                string name = DateTime.Now.ToString("yyyyMMddHHmmssfff"); // 添加毫秒和随机数以区分文件
                                                                          // 获取后缀名
                string ext = Path.GetExtension(file.FileName);
                // 设置上传路径
                string relativePath = $"Uploader/{DateTime.Now:yyyy-MM-dd}-{name}{ext}";
                // 生成文件的绝对路径
                var absolutePath = Path.Combine(webHostEnvironment.WebRootPath, relativePath);

                // 创建上传文件对应的文件夹
                (new FileInfo(absolutePath)).Directory.Create();

                using (var stream = new FileStream(absolutePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // 返回完整的可访问 URL
                string fullUrl = $"{Request.Scheme}://{Request.Host}/{relativePath.Replace("\\", "/")}";
                uploadedFiles.Add(new { success = true, path = fullUrl, originalName = file.FileName });
            }

            return Ok(uploadedFiles);
        }


        /// <summary>
        /// 添加货品图片
        /// </summary>
        /// <param name="procid"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddProductImg(int procid, string img)
        {
            return await productImgService.AddProductImg(procid, img);
        }


        /// <summary>
        /// 根据货品id查询对应图片
        /// </summary>
        /// <param name="procid">货品id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<ProductImg>> GetImgByPId(int procid)
        {
            return await productImgService.GetImgByPId(procid);
        }


        /// <summary>
        /// 修改货品图片（先删除再添加）
        /// </summary>
        /// <param name="procid">货品id</param>
        /// <param name="img">图片</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateImg(int procid, string img)
        {
            return await productImgService.UpdateImg(procid, img);
        }

    }
}
